﻿using DM_IBLL;
using DM_Sqlite.MappingClass;
using DM_TOOLS.Tools;
using Microsoft.AspNetCore.Mvc;

namespace DMSystem_Sqlite_WebAPI.Controllers
{
    [Route("[controller]/[action]")]
    [ApiController]
    public class AccountController : ControllerBase
    {
        private readonly ILogger<AccountController> _logger;
        private readonly IBLL_Login _ibLL_login;
        public AccountController(ILogger<AccountController> logger, IBLL_Login ibLL_login)
        {
            _logger = logger;
            _ibLL_login = ibLL_login;
        }
        [HttpPost]
        //post请求[FromBody]标记参数为对象需要使用json的格式进行传递，然后postman在"Body"框下选择"raw"，参数类型不要写错
        public IActionResult AccountRegister([FromBody] dm_sysauthority user)
        {
            var u = _ibLL_login.LoadEntities(a => a.loginname == user.loginname).FirstOrDefault();
            if (u != null)
            {
                return BadRequest("用户名已存在，无法注册");
            }
            else
            {
                user.password = MD5Encode.GetMD5Encode(user.password, "utf-8");
                user.avatarpath = "icon-user.png";//这是注册默认的头像图片名称
                var isaddsucess = _ibLL_login.AddEntity(user);
                if (isaddsucess)
                {
                    _logger.LogInformation($"Account控制器accountRegister方法,执行成功：{DateTime.Now}");

                    return Ok("注册成功");
                }
                else
                {
                    _logger.LogError($"Account控制器accountRegister方法,执行失败-数据库操作失败：{DateTime.Now}");

                    return BadRequest("注册失败");
                }
            }
        }
        //[Authorize]
        [HttpGet]
        public IActionResult GetAccount(int page, int pagesize)
        {
            //base.HttpContext.Response.Headers.Add("Access-Control-Allow-Credentials", "true");
            //var cookie=base.HttpContext.Request.Headers["Cookie"];
            var data = _ibLL_login.LoadEntities(a => true);
            var datacount = data.Count();
            var pagedata = data.Skip((page - 1) * pagesize).Take(pagesize).OrderBy(a => a.key);
            return Ok(new { pagedata, total = datacount });
        }

        [HttpPost]
        public IActionResult AddAccount([FromBody] dm_sysauthority row)
        {
            //先按照key来排序获得最后一个数据
            var last = _ibLL_login.LoadEntities(a => true).OrderBy(a => a.key).LastOrDefault();
            if (last != null)
            {
                //把要添加的数据的key改为最后一个数据的key+1，这样数据库里就是连续的数据，不会出现断档的key
                row.key = last.key + 1;
            }
            else
            {
                row.key = 1;
            }
            var namelist = _ibLL_login.LoadEntities(a => true).Select(a => a.loginname).ToList();
            //判断是否有重复的用户名
            var isdoublesn = namelist.Contains(row.loginname);
            if (!isdoublesn)
            {
                row.password = MD5Encode.GetMD5Encode(row.password, "utf-8");
                var isaddsucess = _ibLL_login.AddEntity(row);
                if (isaddsucess)
                {
                    _logger.LogInformation($"Account控制器addAccount方法,执行成功：{DateTime.Now}");

                    return Ok("添加成功");
                }
                else
                {
                    _logger.LogError($"Account控制器addAccount方法,执行失败-数据库操作失败：{DateTime.Now}");

                    return BadRequest("添加失败");
                }
            }
            else
            {
                _logger.LogError($"Account控制器addAccount方法,执行失败-用户名重复：{DateTime.Now}");

                return BadRequest("用户名重复");
            }
        }
        [HttpPut]
        public IActionResult EditAccount([FromBody] dm_sysauthority row)
        {
            //先选出你要编辑的账户名
            var youraccount = _ibLL_login.LoadEntities(a => a.loginname == row.loginname).FirstOrDefault();
            row.password = MD5Encode.GetMD5Encode(row.password, "utf-8");
            //头像路径还是保持原来的账户的头像

            youraccount.password = row.password;

            var iseditsucess = _ibLL_login.EditEntity(youraccount);

            if (iseditsucess)
            {
                _logger.LogInformation($"Account控制器editAccount方法,执行成功：{DateTime.Now}");

                return Ok("编辑成功");
            }
            else
            {
                _logger.LogError($"Account控制器editAccount方法,执行失败-数据库操作失败：{DateTime.Now}");

                return BadRequest("编辑失败");
            }
        }
        [HttpDelete]
        public IActionResult DelAccount(int key)
        {
            var data = _ibLL_login.LoadEntities(a => true).Where(a => a.key == key).FirstOrDefault();

            if (data != null)
            {
                var isdelsuccess = _ibLL_login.DeleteEntity(data);
                if (isdelsuccess)
                {
                    _logger.LogInformation($"Account控制器delAccount方法,参数为{key}执行成功：{DateTime.Now}");
                    return Ok("删除成功");
                }
                else
                {
                    _logger.LogError($"Account控制器delAccount方法,参数为{key}执行失败：{DateTime.Now}");
                    return BadRequest("删除失败");

                }
            }
            else
            {
                _logger.LogInformation($"Account控制器delAccount方法,参数为{key}执行失败-找不到数据：{DateTime.Now}");
                return BadRequest("无法删除");
            }

        }

        [HttpPost]
        public IActionResult Upload([FromForm] IFormFile avatar, [FromForm] string loginname)
        {
            //先获得上传图片的名称
            var fileName = avatar.FileName;
            //获得图片保存的地址
            var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "AvarterUpload", fileName);
            //复制图片到保持的地址
            using (var stream = new FileStream(path, FileMode.Create))
            {
                avatar.CopyTo(stream);
            }
            //先查询数据库中此用户名的数据，然后修改数据中图片名称，改为上传后的图片名称，再存入数据库中
            var u = _ibLL_login.LoadEntities(a => a.loginname == loginname).First();
            u.avatarpath = avatar.FileName;
            var iseditsucess = _ibLL_login.EditEntity(u);
            if (iseditsucess)
            {
                _logger.LogInformation($"Account控制器Upload方法,执行成功：{DateTime.Now}");
                u.password = "";
                //如果
                return Ok(u);
            }
            else
            {
                _logger.LogError($"Account控制器Upload方法,执行失败-数据库操作失败：{DateTime.Now}");
                return BadRequest("头像上传失败");
            }

        }
    }
}
